<template>
    <div style="height: 100%; position: relative">
        <el-drawer 
          title="新增" :visible.sync="show_dialog" direction="rtl" size="80%" custom-class="demo-drawer" ref="drawer">
            <div class="demo-drawer__content" ref="content">
                <el-form :model="form" :rules="rules" v-if="show_dialog" ref="editDrawer">
                    <el-form-item label="商家名称:" :label-width="formLabelWidth" prop="store_name">
                         <!-- <el-input v-model="form.store_name"></el-input> -->
                        <el-select v-model="form.store_name" filterable placeholder="请选择">
                            <el-option
                                v-for="item in storesList" :key="item.store_id" :label="item.store_name" :value="item.store_name">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="供应商名称:" :label-width="formLabelWidth" prop="service_suppliers_name">
                        <el-select v-model="form.service_suppliers_name" placeholder="请选择">
                            <el-option
                                v-for="item in supplierList" :key="item.ServiceSuppliersID" 
                                :label="item.SuppliersName" :value="item.ServiceSuppliersName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="应用场景:" :label-width="formLabelWidth" prop="application_scenarios">
                        <el-select v-model="form.application_scenarios" placeholder="请选择">
                            <el-option
                              v-for="item in Scenarios" :key="item.key" :label="item.des" :value="item.des">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="场景二级分类:" :label-width="formLabelWidth" prop="scenarios_sub_category">
                        <el-select v-model="form.scenarios_sub_category" placeholder="请选择">
                            <el-option
                                v-for="item in SubCateScenarios" :key="item.scenarios_sub_code"
                                :label="item.scenarios_sub_category" :value="item.scenarios_sub_category">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="线路ID:" :label-width="formLabelWidth" prop="ai_call_line_id">
                        <el-select
                            v-model="form.ai_call_line_id"
                            clearable filterable :filter-method="handleFilter" @focus="handleLineFocus"
                            placeholder="请选择: 线路ID / 线路号码 / 线路名称 / 供应商 / 备注">
                            <el-option
                                v-for="item in lineList"
                                :key="item.id"
                                :label="`${item.line_index} / ${item.line_number} / ${item.line_name} / ${item.supplier_name} / ${item.remark}`"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="用户注册:" :label-width="formLabelWidth" prop="registered">
                        <el-select v-model="form.registered" placeholder="请选择">
                            <el-option
                                v-for="item in regType" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                        <span class="color-info" style="margin-left: 10px;">备注：控制外呼用户是否注册为车家佳用户</span>
                    </el-form-item>
                    <el-form-item label="回调地址:" :label-width="formLabelWidth" prop="postback_address">
                        <el-input v-model="form.postback_address"></el-input>
                    </el-form-item>
                    <el-form-item label="应用服务:" :label-width="formLabelWidth" prop="application_services">
                        <el-select v-model="form.application_services" placeholder="请选择">
                            <el-option v-for="item in Services" :key="item.key" :label="item.des" :value="item.des"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="话术id:" :label-width="formLabelWidth" prop="supplier_product_id">
                        <el-input v-model="form.supplier_product_id"></el-input>
                    </el-form-item>
                    <el-form-item label="话术名称:" :label-width="formLabelWidth" prop="product_description">
                        <el-input v-model="form.product_description"></el-input>
                    </el-form-item>
                    <el-form-item label="话术传参类型:" :label-width="formLabelWidth" prop="param_flag">
                        <el-select v-model="form.param_flag" placeholder="请选择">
                            <el-option key="1" label="话术统一传参模式" value="1"></el-option>
                            <el-option key="2" label="明细传参模式" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="话术传参:" :label-width="formLabelWidth" prop="param_context">
                        <el-input v-model="form.param_context"></el-input>
                    </el-form-item>
                    <el-form-item label="话术模板:" :label-width="formLabelWidth" prop="file_save_path">
                        <el-input v-model="form.file_save_path"></el-input>
                    </el-form-item>
                    <el-form-item label=" 是否二次质检:" :label-width="formLabelWidth" prop="second_quality">
                        <el-select v-model="form.second_quality" placeholder="请选择">
                            <el-option key="0" label="否" value="0"></el-option>
                            <el-option key="1" label="是" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="关联团购:" :label-width="formLabelWidth" prop="second_quality">
                        <el-select class="el-select-small" v-model="group_buy_type" placeholder="请选择" @change="changeTg">
                            <el-option key="0" label="请选择" value="0"></el-option>
                            <el-option key="2" label="新车团购" value="2"></el-option>
                            <el-option key="1" label="售后团购" value="1"></el-option>
                        </el-select>
                        <!-- <el-select class="el-select-small" v-model="form.second_quality" placeholder="请输入">
                            <el-option key="0" label="否" value="0"></el-option>
                            <el-option key="1" label="是" value="1"></el-option>
                        </el-select> -->
                        <el-select
                            v-model="group_buy_id"
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入团购名称"
                            :remote-method="remoteMethod"
                            :loading="loading"
                            class="el-select-small"
                            :disabled="value_disable">
                            <el-option
                              v-for="(item,index) in options"
                              :key="index"
                              :label="group_buy_type == 2 ? item.ncgb_title_name : item.asgb_title_name"
                              :value="group_buy_type == 1 ? item.asgb_id : item.ncgb_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div class="demo-drawer__footer">
                <el-button @click="cancelForm">取 消</el-button>
                <el-button type="primary" @click="handleClose" :loading="loading" v-show="type !== 'show'">
                    {{ loading ? "提交中 ..." : "确 定" }}
                </el-button>
            </div>
        </el-drawer>
    </div>
</template>
<script>
import { dateFormatter } from "@/common/js/util";
export default {
    props: ["dialog"],
    data() {
        return {
            loading: false,
            formLabelWidth: "180px",
            show_dialog: false, //弹窗显示
            form: {
                store_name: "",
                service_suppliers_name: "",
                application_scenarios: "",
                scenarios_sub_category: "",
                application_services: "",
                supplier_product_id: "",
                product_description: "",
                ai_call_line_id: "",
                registered: "",
                postback_address: "",
                param_flag: "",
                second_quality: "",
                param_context: "",
                file_save_path: "",
            },
            group_buy_type: "",
            group_buy_id: "",
            value_disable: false,
            options: [],
            gid: "",
            rules: {
                store_name: [{ required: true, message: "商家名称不能为空" }],
                service_suppliers_name: [
                    { required: true, message: "供应商名称不能为空" },
                ],
                application_scenarios: [
                    { required: true, message: "应用场景不能为空" },
                ],
                scenarios_sub_category: [
                    { required: true, message: "二级分类不能为空" },
                ],
                ai_call_line_id: [
                    { required: true, message: "请选择线路ID", trigger: "change" },
                ],
                registered: [
                    { required: true, message: "请选择用户注册状态", trigger: "change" },
                ],
                application_services: [{ required: true, message: "应用服务不能为空" }],
                supplier_product_id: [{ required: true, message: "话术id不能为空" }],
                product_description: [{ required: true, message: "话术名称不能为空" }],
            },
            type: "",
            row: "",
            Services: "", //服务类型
            Scenarios: "",
            SubCateScenarios: "",
            supplierList: "",
            storesList: [],
            lineList: [],
            lineListCopy: [],
            regType: [
                { label: '是', value: '1' },
                { label: '否', value: '0' }
            ]
        }
    },
    created() {
        this.default_data();
    },
    methods: {
        changeTg(){
            this.options = [];
            this.group_buy_id = "";
        },
        remoteMethod(query){
            if (this.group_buy_type == "") {
                this.$message.warning("请先选择团购类型!");
                return;
            }
            if (this.group_buy_type == 2) {
                let data = {
                    title_name:query
                }
                this.$http.post('/admin/newCarGroupBuy/index.php?act=groupBuy&op=list', data).then(res=>{
                    this.options = res.data.list
                })
            } else if (this.group_buy_type == 1) {
                let data = {
                    title_name:query
                }
                this.$http.post('/admin/afterSalesGroupBuy/index.php?act=groupBuy&op=list', data).then(res=>{
                    this.options = res.data.list
                })
            }
        },
        default_data() {
            //服务类型
            this.getServices();
            //应用场景
            this.getScenarios();
            //场景二极分类
            this.getSubCateScenarios();
            //供应商名称
            this.supplierListFn();
            //供应商
            this.getStores();
            //线路ID
            this.getLineList();
        },
        handleFilter(val) {
            if (val) {
                this.lineList = this.lineListCopy.filter((item) => {
                    const value = `${item.line_index} / ${item.line_number} / ${item.line_name} / ${item.supplier_name} / ${item.remark}`;
                    if (value.includes(val)) {
                        return item;
                    }
                });
            } else {
                this.handleLineFocus();
            }
        },
        handleLineFocus() {
            this.lineList = this.lineListCopy;
        },
        getLineList() {
            this.$http.post("/admin/dataService/index.php?act=callLine&op=getCallLineList").then((res) => {
                if (res.code == 1) {
                    this.lineList = res.data;
                    this.lineListCopy = [...res.data];
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.$message.error(err);
            });
        },
        getStores() {
            this.$http.post("/admin/dataService/index.php?act=merchantSet&op=getStores").then((res) => {
                if (res.code == 1) {
                    this.storesList = res.data;
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.$message.error(err);
            });
        },
        supplierListFn() {
            this.$http.post("/admin/dataService/index.php?act=merchantSet&op=supplierList").then((res) => {
                if (res.code == 1) {
                    this.supplierList = res.data.list;
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.$message.error(err);
            });
        },
        getSubCateScenarios() {
            this.$http.post("/admin/dataService/index.php?act=merchantSet&op=getSubCateScenarios").then((res) => {
                if (res.code == 1) {
                    this.SubCateScenarios = res.data;
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.$message.error(err);
            });
        },
        getScenarios() {
            this.$http.post("/admin/dataService/index.php?act=merchantSet&op=getScenarios").then((res) => {
                if (res.code == 1) {
                    this.Scenarios = res.data;
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.$message.error(err);
            });
        },
        getServices() {
            this.$http.post("/admin/dataService/index.php?act=merchantSet&op=getServices").then((res) => {
                if (res.code == 1) {
                    this.Services = res.data;
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.$message.error(err);
            });
        },
        show_dialog_fn(type, row) {
            this.type = type;
            this.show_dialog = true;
            if (type === "add") {
                this.form = {
                    store_name: "",
                    service_suppliers_name: "",
                    application_scenarios: "",
                    scenarios_sub_category: "",
                    application_services: "",
                    supplier_product_id: "",
                    product_description: "",
                    param_flag: "",
                    second_quality: "1",
                    param_context: "",
                    file_save_path: "",
                    ai_call_line_id: "",
                    registered: "",
                    postback_address: ""
                };
            } else if (type === "edit") {
                this.row = row;
                this.getItemDetail(row.id);
            }
        },
        cancelForm() {
            this.loading = false;
            this.show_dialog = false;
            clearTimeout(this.timer);
        },
        handleClose() {
            this.$refs.editDrawer.validate((valid) => {
                if (valid) {
                    let {
                        store_name,
                        service_suppliers_name,
                        application_scenarios,
                        scenarios_sub_category,
                        application_services,
                        supplier_product_id,
                        product_description,
                        param_flag,
                        second_quality,
                        param_context,
                        ai_call_line_id,
                        registered,
                        postback_address,
                        file_save_path,
                    } = this.form;
                    let findFn = (arr, key, value) => {
                        return arr.find((item) => item[key] == value);
                    };
                    const store = findFn(this.storesList, "store_name", store_name)
                    if (!store) {
                        this.form.store_name = ''
                        return this.$message.error('商家名称不存在，请重新选择')
                    }
                    let data = {
                        store_name,
                        store_id: store.store_id,
                        service_suppliers_name,
                        service_suppliers_id: findFn(this.supplierList, "ServiceSuppliersName", service_suppliers_name).ServiceSuppliersID,
                        application_scenarios,
                        application_scenarios_key: findFn(this.Scenarios, "des", application_scenarios).key,
                        scenarios_sub_category,
                        scenarios_sub_code: findFn(this.SubCateScenarios, "scenarios_sub_category", scenarios_sub_category).scenarios_sub_code,
                        application_services,
                        application_services_key: findFn(this.Services, "des", application_services).key,
                        supplier_product_id,
                        product_description,
                        param_flag,
                        second_quality,
                        param_context,
                        file_save_path,
                        ai_call_line_id,
                        registered,
                        postback_address
                    };
                    data.group_buy_type = this.group_buy_type;
                    data.group_buy_id = isNaN(this.group_buy_id) ? this.gid : this.group_buy_id;
                    if ((data.group_buy_type == 1 || data.group_buy_type == 2) && data.group_buy_id == "") {
                        this.$message.warning("请选择团购")
                        return
                    }
                    if (this.type === "edit") {
                        data.id = this.row.id;
                        this.editItemDetail(data);
                    } else if (this.type === "add") {
                        this.addItemDetail(data);
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        getItemDetail(id) {
            this.$http.post("/admin/dataService/index.php?act=merchantSet&op=getMerchantWord", { id }).then((res) => {
                if (res.code != 1) {
                    this.$message.warning(res.msg);
                    this.show_dialog = false;
                    return;
                }
                //处理服类型
                if (res.data.ServiceDescription) {
                    res.data.application_services = res.data.ServiceDescription.split(",");
                }
                this.group_buy_type = res.data.group_buy_type == 0 ? "" : res.data.group_buy_type;
                this.gid = res.data.group_buy_id == 0 ? "" : res.data.group_buy_id;
                this.group_buy_id = res.data.group_buy_title;
                //处理时间
                let time1 = res.data.ServiceAvailableTime;
                let time2 = res.data.ServiceEndTime;
                if (time1) {
                    time1 = dateFormatter("YYYY-MM-DD", time1 * 1000);
                }
                if (time2) {
                    time2 = dateFormatter("YYYY-MM-DD", time2 * 1000);
                }
                res.data.time_end_start = [time1, time2];
                if (Number(res.data.ai_call_line_id) <= 0)
                    res.data.ai_call_line_id = "";
                this.form = res.data;
            }).catch((err) => {
                this._message("error", err);
            });
        },
        addItemDetail(data) {
            this.$http.post("/admin/dataService/index.php?act=merchantSet&op=addMerchantWord", data).then((res) => {
                if (res && res.code == 1) {
                    this.show_dialog = false;
                    this.$parent.getListData();
                    this.$message.success(res.msg);
                } else {
                    this.$message.warning(res.msg);
                }
            }).catch((err) => {
                this._message("error", err);
            });
        },
        editItemDetail(data) {
            this.$http.post(`/admin/dataService/index.php?act=merchantSet&op=updateMerchantWord`, data).then((res) => {
                if (res.code == 1) {
                    this.show_dialog = false;
                    this.$message.success(res.msg);
                    this.$parent.getListData();
                } else {
                    this.$message.warning(res.msg);
                }
            }).catch((err) => {
                this._message("error", err);
            });
        }
    }
}
</script>

<style lang="scss" scoped>
.el-form {
  // width: 560px;
  padding-left: 10px;
}

.el-select /deep/.el-input {
  width: 360px;
}
.el-select-small /deep/.el-input {
  width: 180px;
}
.plantTable /deep/.el-input {
  width: auto;
}
form /deep/.el-input {
  width: 360px;
}

.demo-drawer__content {
  position: absolute;
  top: 0;
  bottom: 60px;
  width: 100%;
  overflow-y: auto;
}

/deep/.el-drawer__body {
  position: absolute;
  top: 77px;
  bottom: 0;
  width: 100%;
  overflow: auto;
  padding-bottom: 60px;
}

.demo-drawer__footer {
  position: absolute;
  bottom: 10px;
  left: 20px;
}

.avatar-uploader /deep/.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader /deep/.el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.row_line {
  border-bottom: 1px dashed #d7d8dc;
}
.goodsInfo {
  display: flex;
  align-items: center;
}
</style>
